<?php

class LessonStudentController extends \BaseController {

    /**
     * 返回课程的所有学生.
     *
     * @param $lessonId 待查询的课程id
     *
     * @return \Illuminate\Http\JsonResponse
     *
     * 返回的JSON格式：
     * [
     *  {
     *      'username': '用户名',
     *      'email': '用户的电子邮件',
     *      'id': '用户的id'
     *  },
     *  .....
     * ]
     */
    public function index($lessonId)
    {
        $students = Lesson::findOrFail($lessonId)->student()->get([
            'username', 'email', 'users.id'
        ])->toArray();

        return Response::json($students);
    }


    /**
     * 新增学生，提交的变量名为：student，值可以是用户的id、邮件地址或用户名
     *
     * @param $lessonId
     * @return \Illuminate\Http\Response
     */
    public function store($lessonId)
    {
        $targetLesson = Lesson::findOrFail($lessonId);

        $mixedQuery = Input::get('student');

        $targetStudent = User::where('id', $mixedQuery)
            ->orWhere('username', $mixedQuery)
            ->orWhere('email', $mixedQuery)
            ->firstOrFail();

        $targetLesson->student()->save($targetStudent);

        return Response::make('', 200);
    }


    /**
     * 显示某个学生的个人信息.
     *
     * @param $lessonId 待查询的课程id
     * @param $studentId 待查询的学生id
     * @return \Illuminate\Http\JsonResponse
     *
     * 返回的JSON格式：
     * {
     *  "username": "用户名",
     *  "email": "用户的电子邮箱",
     *  "description": "用户的个人简介",
     *  "id": "id"
     * }
     */
	public function show($lessonId, $studentId)
    {
        $targetPivot = Lesson_Student::where('lesson_id', $lessonId)
            ->where('student_id', $studentId)
            ->firstOrFail();

        $keys = ['username', 'id', 'description', 'email'];
        return Response::json( $this->getSectionalValuesFromModel($targetPivot['student'], $keys) );
    }

    public function update($lessonId, $studentId)
    {
        return $this->defaultPreventedOperation();
    }

    /**
     * 删除某个学生，实际上是把学生从某个课程中移除，而并非移除用户.
     *
     * @param $lessonId  待删除的学生所在的课程的id
     * @param $studentId 待删除的学生
     * @return \Illuminate\Http\Response
     */
	public function destroy($lessonId, $studentId)
	{
        $targetPivot = Lesson_Student::where('lesson_id', $lessonId)
            ->where('student_id', $studentId)
            ->firstOrFail();

        $targetPivot->delete();

        return Response::make('', 200);
	}

    protected function defaultPreventedOperation()
    {
        return Response::make('', 401);
    }

}
